"""
AI Agent 的工具注册表
包含 OCR、订单查询、退款链接生成等工具
"""

import os
import re
import json
import base64
import requests
from typing import Dict, Any
from langchain.tools import BaseTool


class OCRTool(BaseTool):
    """OCR 图片识别工具，用于识别发票信息"""

    name: str = "ocr_image"
    description: str = "识别上传的发票图片，提取订单号、金额、日期等信息。返回包含字段的JSON对象：{amount, date, order_id}"

    def _run(self, image_b64: str) -> str:
        """
        执行 OCR 识别

        Args:
            image_b64: base64 编码的图片数据

        Returns:
            JSON 字符串，包含识别结果
        """
        try:
            # 检查是否配置了 Azure OCR
            azure_endpoint = os.getenv('AZURE_OCR_ENDPOINT')
            azure_key = os.getenv('AZURE_OCR_KEY')

            if not azure_endpoint or not azure_key:
                # 使用模拟 OCR 结果（用于演示）
                return json.dumps({
                    "amount": "299.00",
                    "order_id": "ORD20250401",
                    "date": "2024-04-01",
                    "status": "recognized"
                })

            # 调用 Azure OCR API
            headers = {
                'Ocp-Apim-Subscription-Key': azure_key,
                'Content-Type': 'application/json'
            }

            data = {
                "content": image_b64
            }

            response = requests.post(
                f"{azure_endpoint}/vision/v3.2/ocr",
                headers=headers,
                json=data,
                timeout=30
            )

            if response.status_code == 200:
                result = response.json()

                # 从 OCR 结果中提取信息
                extracted_text = ""
                if 'regions' in result:
                    for region in result['regions']:
                        for line in region['lines']:
                            for word in line['words']:
                                extracted_text += word['text'] + " "

                # 使用正则表达式提取关键信息
                amount_match = re.search(r'[\$¥￥]?(\d+(?:,\d{3})*(?:\.\d{2})?)', extracted_text)
                order_match = re.search(r'订单[号:]*([A-Z0-9]+)', extracted_text, re.IGNORECASE)
                date_match = re.search(r'(\d{4}[-/]\d{1,2}[-/]\d{1,2})', extracted_text)

                return json.dumps({
                    "amount": amount_match.group(1) if amount_match else "0.00",
                    "order_id": order_match.group(1) if order_match else "UNKNOWN",
                    "date": date_match.group(1) if date_match else "UNKNOWN",
                    "raw_text": extracted_text[:200]  # 保留前200个字符用于调试
                })
            else:
                return json.dumps({
                    "error": f"OCR API 调用失败: {response.status_code}",
                    "amount": "0.00",
                    "order_id": "UNKNOWN",
                    "date": "UNKNOWN"
                })

        except Exception as e:
            return json.dumps({
                "error": f"OCR 处理异常: {str(e)}",
                "amount": "0.00",
                "order_id": "UNKNOWN",
                "date": "UNKNOWN"
            })


class QueryOrderTool(BaseTool):
    """订单查询工具"""

    name: str = "query_order"
    description: str = "根据订单号查询订单状态，返回包含状态、金额、可退款信息的JSON对象"

    def _run(self, order_id: str) -> str:
        """
        查询订单信息

        Args:
            order_id: 订单号

        Returns:
            JSON 字符串，包含订单信息
        """
        try:
            mock_url = os.getenv('ORDER_MOCK_URL', 'http://order-mock:5000')

            response = requests.get(
                f"{mock_url}/order/{order_id}",
                timeout=10
            )

            if response.status_code == 200:
                return response.text
            else:
                return json.dumps({
                    "error": f"订单查询失败: {response.status_code}",
                    "order_id": order_id,
                    "status": "unknown",
                    "amount": "0.00",
                    "refundable": False
                })

        except requests.exceptions.RequestException as e:
            return json.dumps({
                "error": f"网络请求异常: {str(e)}",
                "order_id": order_id,
                "status": "error",
                "amount": "0.00",
                "refundable": False
            })


class GenerateRefundLinkTool(BaseTool):
    """退款链接生成工具"""

    name: str = "gen_refund_link"
    description: str = "为指定订单生成退款链接"

    def _run(self, order_id: str) -> str:
        """
        生成退款链接

        Args:
            order_id: 订单号

        Returns:
            退款链接字符串
        """
        try:
            # 在实际应用中，这里应该调用真实的退款系统API
            # 这里使用模拟链接
            base_url = os.getenv('REFUND_BASE_URL', 'https://refund.acme.com')
            return f"{base_url}/refund/{order_id}?token=demo_{order_id}"

        except Exception as e:
            return f"退款链接生成失败: {str(e)}"


class SendEmailTool(BaseTool):
    """邮件发送工具（可选扩展功能）"""

    name: str = "send_email"
    description: str = "发送通知邮件给用户"

    def _run(self, email_data: str) -> str:
        """
        发送邮件

        Args:
            email_data: JSON字符串，包含收件人、主题、内容

        Returns:
            发送结果
        """
        try:
            data = json.loads(email_data)
            # 这里应该集成实际的邮件服务
            # 暂时返回模拟结果
            return json.dumps({
                "status": "success",
                "message": f"邮件已发送至 {data.get('to', 'unknown')}",
                "subject": data.get('subject', '通知')
            })

        except Exception as e:
            return json.dumps({
                "status": "error",
                "message": f"邮件发送失败: {str(e)}"
            })


# 导出所有工具类
__all__ = [
    'OCRTool',
    'QueryOrderTool',
    'GenerateRefundLinkTool',
    'SendEmailTool'
]
